package com.uy.system.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.uy.system.common.constant.SystemConstants;
import com.uy.system.model.enums.HttpCode;
import com.uy.system.utils.ResponseUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author LY
 * @create 2024/4/23 9:19
 * @Description token校验过滤器
 */
@Component
public class GlobalFilter extends OncePerRequestFilter {

    /**
     * 获取请求头token,校验token是否合法
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(SystemConstants.ACCESS_TOKEN);
        System.out.println("token="+token + ",是否登录=" + StpUtil.isLogin());
        if (StrUtil.isNotBlank(token)){
            Object loginId = StpUtil.getLoginIdByToken(token);
            System.out.println("loginId="+loginId);
            if (StrUtil.isEmpty((CharSequence) loginId)){
                ResponseUtils.writeErrMsg(response, HttpCode.INVALID_TOKEN);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}
